package com.zhuxi.filter;

import com.alibaba.fastjson.JSONObject;
import com.zhuxi.dao.LagouTokenRepository;
import com.zhuxi.pojo.LagouToken;
import com.zhuxi.pojo.LoginRecords;
import com.zhuxi.util.GlobUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.domain.Example;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Slf4j
@Component // 让容器扫描到，等同于注册了
public class CookieFilter implements GlobalFilter, Ordered {

    @Autowired
    private LagouTokenRepository lagouTokenRepository;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        String[] split = path.split("/");
        if ("user".equals(split[2]) || "code".equals(split[2])) {
            //注册接口ip防暴刷
            if ("user".equals(split[2]) && "register".equals(split[3])) {
                LoginRecords loginRecords = new LoginRecords();
                loginRecords.setIp(request.getRemoteAddress().getHostString());
                loginRecords.setLoginTime(new Date());
                if (GlobUtils.isPass()) {
                    GlobUtils.loginRecordsList.add(loginRecords);
                } else {
                    String message = "操作频繁，请稍后再试！";
                    byte[] bits = message.getBytes(StandardCharsets.UTF_8);
                    DataBuffer buffer = response.bufferFactory().wrap(bits);
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                    return response.writeWith(Mono.just(buffer));
                }

            }
            return chain.filter(exchange);
        }
        //cookie校验
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> tokens = cookies.get("token");
        if (tokens != null && tokens.size() != 0) {
            String token = tokens.get(0).getValue();
            LagouToken lagouToken = new LagouToken();
            lagouToken.setToken(token);
            Example<LagouToken> example = Example.of(lagouToken);
            List<LagouToken> all = lagouTokenRepository.findAll(example);
            if (all != null && all.size() != 0) {
                return chain.filter(exchange);
            }
        }

        String message = "未登录，请先进行登录！";
        byte[] bits = message.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
